package cn.qidisoft.edu.hzjt.controller.xb;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import cn.qidisoft.core.common.context.ApplicationContextConfigUtil;
import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.DateUtil;
import cn.qidisoft.core.util.file.FileUtil;
import cn.qidisoft.core.util.uuid.UUIDGenerator;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.xb.TrainingDocAttEn;
import cn.qidisoft.edu.hzjt.service.xb.ITrainingDocAttService;
import cn.qidisoft.edu.hzjt.utils.CommonUtils;
import cn.qidisoft.edu.hzjt.utils.LogType;

/**
 * 
 * @ClassName: TrainingDocController   
 * @Description:4.2教师继续教育与培训系统  JKY_JYPX_PXWJ
 * 							一、培训文件
 * @author xb12369   
 * @date 2018年11月27日   
 *
 */
@Controller
@RequestMapping(value="/trainingDoc")
public class TrainingDocController {

	protected static final LoggerAdapter LOGGER = LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);

	private static String upload = null;
	static {
		upload = ApplicationContextConfigUtil.getString("file.path", null);
	}

	private static Map<String, List<TrainingDocAttEn>> picMap = new HashMap<>();

	@Autowired
	private ITrainingDocAttService service;


	@RequestMapping(value = "/index")
	public String index(ModelMap model, HttpServletRequest request) {
		request.setAttribute("msg", BaseController.getParameter("msg"));
		BaseController.removeParameter("msg");

		return "xb/JKY_JYPX_PXWJ/list_TrainingDoc";
	}

	@RequestMapping(value = "/list")
	@ResponseBody
	public ResponseResult list(
			ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage,
			TrainingDocAttEn data) {
		try {
			data.setGID(UUIDGenerator.genReqID());
			Page page = new Page();
			page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
			page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
			BaseController.setSortByColumn(request, "createtime", "desc");
			data.setOrderField((String) request.getAttribute("orderField"));
			data.setOrderFlag((String) request.getAttribute("orderFlag"));
			PaginationBean<TrainingDocAttEn> paginationBean = service.queryPageList(data,page);
			ResponseResult result = new ResponseResult();
			result.setTotal(paginationBean.getTotalRecords());
			result.setRows(paginationBean.getPageList());
			return result;
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		return null;
	}

	@SysLogger(description = "培训文件管理信息", moduleName = "培训文件管理", method = "新增保存")
	@RequestMapping(value = "/save", method = RequestMethod.GET)
	public void save(HttpServletRequest request,HttpServletResponse resp) {
		String result = "1";
		PrintWriter pw = null;
		try {
			String keyWords1 = request.getParameter("keyWords1");
			String fileType1 = request.getParameter("fileType1");
			UserEmployee userEmployee = (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
			String gid = UUIDGenerator.genReqID();

			String path = upload;
			List<TrainingDocAttEn> docFileResourceList = picMap.get(String.valueOf(userEmployee.getUserid()));
			if (docFileResourceList != null && !docFileResourceList.isEmpty()) {
				MultipartFile file = null;
				String filePath =CommonUtils.createSaveFilePath("JKY_JYPX_PXWJ", userEmployee.getUserid() );
				for (TrainingDocAttEn r : docFileResourceList) {

					file = r.getMufile();
					String name = file.getOriginalFilename();// 获取上传文件名
					InputStream in = r.getInputStream();// 获取文件对象
					int pos = name.lastIndexOf(".");
					String lastname = name.substring(pos, name.length());
					// 文件保存的路径
					String savePath = path + CommonUtils.fileSeprator+ filePath;
					FileUtil.saveFile(savePath, in, r.getgID() + lastname);
					r.setgID(r.getgID());// 附件id
					r.setFileName(name);
					r.setGID(gid);
					r.setCreatorId(userEmployee.getUid());
					r.setCreatorName(userEmployee.getXm());
					r.setCreateTime(DateUtil.formatDate2Str((new Date()), DateUtil.YYYY_MM_DD_FORMAT));
					r.setKeyWords(keyWords1);
					r.setFileType(fileType1);
				}
				service.batchInserts(docFileResourceList);
				//一旦上传成功需要清空，否则下一次上传的时候又刚一遍了~
				picMap.remove(String.valueOf(userEmployee.getUserid()));
			}
			pw = resp.getWriter();
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("添加信息 add [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			result = "-1";
		}

		pw.println(result);
		pw.close();
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public String delete(ModelMap model, HttpServletRequest request) {
		try {
			String[] idList = request.getParameter("idList").split(",");
			for (int i = 0; i < idList.length; i++) {
				TrainingDocAttEn data = new TrainingDocAttEn();
				data.setFileId(Integer.parseInt(idList[i]));
				service.delete(data);
			}

			BaseController.setParameter("msg", "删除成功");
			return "redirect:index";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}

	/**
	 * 
	 * @Title: loadFile   
	 * @Description: 附件上传
	 * @param @param file
	 * @param @param request
	 * @param @param response    参数   
	 * @return void    返回类型   
	 * @throws
	 */
	@RequestMapping(value = "/source_upload", method = RequestMethod.POST)
	public @ResponseBody void source_upload(@RequestParam("file") MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) {
		List<TrainingDocAttEn> list = new ArrayList<>();
		UserEmployee userEmployee = (UserEmployee) request.getSession()
				.getAttribute(Constant.LOGIN_CONSOLE_USER);
		List<TrainingDocAttEn> docFileResourceList = picMap
				.get(String.valueOf(userEmployee.getUserid()));
		// 本地env配置路径
		String path = upload;
		try {
			String gid = UUID.randomUUID().toString();
			String name = file.getOriginalFilename();// 获取上传文件名
			// 获取文件后缀名称
			String extend = FilenameUtils.getExtension(name);
			TrainingDocAttEn docFile = new TrainingDocAttEn();
			String filePath =CommonUtils.createSaveFilePath("JKY_JYPX_PXWJ", userEmployee.getUserid() );
			if (!file.isEmpty()) {
				// 文件的大小
				docFile.setFileSize(String.valueOf(FileUtil.FormetFileSize(Long.valueOf(file.getSize()))));
				docFile.setFileName(name);
				docFile.setgID(gid);
				docFile.setExtension(FileUtil.getFileExtendName(name).toLowerCase());
				docFile.setMufile(file);
				docFile.setInputStream(file.getInputStream());
				/**
				 * 2018年12月9日 
				 * 当前业务目录/用户ID/上传当前时间（到天）/随机生成uuid文件名称
				 */
				docFile.setFilePath(filePath + gid + "." + extend);
				docFile.setSysfilepath(path + CommonUtils.fileSeprator+ filePath + gid + "." + extend);
				if (docFileResourceList != null && docFileResourceList.size() > 0) {
					docFileResourceList.add(docFile);
					picMap.put(String.valueOf(userEmployee.getUserid()), docFileResourceList);
				} else {
					list.add(docFile);
					picMap.put(String.valueOf(userEmployee.getUserid()), list);
				}
				LOGGER.info("附件上传成功！");
			}
			PrintWriter writer = null;
			TrainingDocAttEn docFile2 = new TrainingDocAttEn();
			docFile2.setFilePath(docFile.getFilePath());
			// 文件名称
			docFile2.setFileName(docFile.getFileName());
			docFile2.setSysfilepath(path + CommonUtils.fileSeprator+ filePath + gid + "." + extend);
			writer = response.getWriter();
			String json = JSONObject.toJSONString(docFile2);
			writer.write(json);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 新增删除服务器的文件
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deletefile", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> deleteFile(HttpServletRequest request) {

		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			UserEmployee userEmployee = (UserEmployee) request.getSession()
					.getAttribute(Constant.LOGIN_CONSOLE_USER);

			// env配置路径
			String path = upload;

			String filepath = request.getParameter("filepath");
			LOGGER.info("文件的原始路径===" + filepath);
			// 文件的全路径
			String fullpath = null;
			// 文件名称
			String filename = null;
			// 文件名无后缀
			String fileNoSuffix = null;

			if (filepath.indexOf("prefix") == -1) {
				// 文件的文件名称
				fileNoSuffix = filepath.split(",")[0];
				String sec = filepath.split(",")[1];
				// 文件的后缀
				String suffix = sec.substring(sec.indexOf("."));
				// 文件名无后缀加上后缀
				filename = fileNoSuffix + suffix;
				// 文件的全路径
				fullpath = path + "/" + fileNoSuffix;
				// FileUtil.deleteFile(fullpath, filename);//删除文件目录下面的文件
				// FileUtils.forceDelete(new File(fullpath)); //删除文件目录
			} else {
				return dataMap;
			}

			List<TrainingDocAttEn> noticeNewsFilepathList = picMap
					.get(String.valueOf(userEmployee.getUserid()));

			// 删除list里面前台删除的前台信息图片附件表
			if (noticeNewsFilepathList != null && !noticeNewsFilepathList.isEmpty()) {
				for (TrainingDocAttEn noticenewsfilepath : noticeNewsFilepathList) {
					if (noticenewsfilepath.getFileName().equals(fileNoSuffix)) {
						noticeNewsFilepathList.remove(noticenewsfilepath);
						break;
					}
				}
			}
			// 先删除
			picMap.remove(userEmployee.getUserid());
			// 后添加
			picMap.put(String.valueOf(userEmployee.getUserid()), noticeNewsFilepathList);
			dataMap.put("success", "0000");
			return dataMap;
		} catch (Exception e) {
			dataMap.put("success", "-9999");
			return dataMap;
		}
	}

	/**
	 * 
	 * @Title: source_upload_update   
	 * @Description: 删除附件
	 * @param @param fileId
	 * @param @param request
	 * @param @param response
	 * @param @return    参数   
	 * @return Map<String,Object>    返回类型   
	 * @throws
	 */
	@RequestMapping(value = "/source_upload_update", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> source_upload_update(@RequestParam("fileId") String fileId,
			@RequestParam("filePath") String filePath,
			HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			//删除表记录
			TrainingDocAttEn attEntity = new TrainingDocAttEn();
			attEntity.setFileId(Integer.parseInt(fileId));

			TrainingDocAttEn newAttEntity = service.queryByFileId(attEntity);
			filePath = newAttEntity.getFilePath();
			service.delete(newAttEntity);

			//删除原始文件
			File file = new File(upload + CommonUtils.fileSeprator+ filePath);
			file.delete();

			//删除目录：实际上是删除最后一节也就是日期文件夹
			try {
				FileUtils.forceDelete(new File(upload + CommonUtils.fileSeprator+ filePath.substring(0,filePath.lastIndexOf("\\")))); //如果文件中所有的文件被删除了，还需要删除文件目录
			} catch (Exception e) {

			}

			dataMap.put("success", "0000");
		} catch (Exception e) {
			LOGGER.error("调用services网络异常", e);
			dataMap.put("success", "-9999");
		}
		return dataMap;
	}

	/*************************************************************华丽的分隔符*************************************************************************************************/
	@RequestMapping(value = "/person_download_index")
	public String person_download_index(ModelMap model, HttpServletRequest request) {
		request.setAttribute("msg", BaseController.getParameter("msg"));
		BaseController.removeParameter("msg");

		return "xb/JKY_JYPX_PXWJ/list_TrainingDocDownLoad";
	}

	@RequestMapping(value = "/person_download_list")
	@ResponseBody
	public ResponseResult person_download_list(
			ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage,
			TrainingDocAttEn data) {
		try {
			data.setGID(UUIDGenerator.genReqID());
			Page page = new Page();
			page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
			page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
			BaseController.setSortByColumn(request, "createtime", "desc");
			data.setOrderField((String) request.getAttribute("orderField"));
			data.setOrderFlag((String) request.getAttribute("orderFlag"));
			PaginationBean<TrainingDocAttEn> paginationBean = service.queryPageList(data,page);
			ResponseResult result = new ResponseResult();
			result.setTotal(paginationBean.getTotalRecords());
			result.setRows(paginationBean.getPageList());
			return result;
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		return null;
	}

}
